#include"windows.h"
#include"tlhelp32.h"
#include<tchar.h>


//提升权限
BOOL SetPrivilege(LPCTSTR lpszPrivilege, BOOL bEnablePrivilege)
{
	TOKEN_PRIVILEGES tp;
	HANDLE hToken;
	LUID luid;

	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
	{
		_tprintf(L"LookupPrivilegeValue error: %u\n", GetLastError());
		return FALSE;
	}
	if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
	{
		_tprintf(L"LookupPrivilegeValue error: %u\n", GetLastError());
		return FALSE;
	}
	tp.PrivilegeCount = 1;
	tp.Privileges[0].Luid = luid;
	if (bEnablePrivilege)
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	else
		tp.Privileges[0].Attributes = 0;
	//enable the privilege or disable all privileges.
	if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
	{
		_tprintf(L"AdjustTokenPrivileges error: %u\n", GetLastError());
		return FALSE;
	}
	if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
	{
		_tprintf(L"the token does nothave rhe specified privilege .\n");
		return FALSE;
	}
	return TRUE;
}

BOOL EjectDll(DWORD dwPID, LPCTSTR szDllName)
{
	BOOL bMore = FALSE, bFound = FALSE;
	HANDLE hSnapshot, hProcess, hThread;
	HMODULE hModule = NULL;
	MODULEENTRY32 me = { sizeof(me) };
	LPTHREAD_START_ROUTINE pThreadProc;
	//dwPID=notepad进程的PID
	//使用TH32CS_SNAPMODULE参数获取加载到notepad进程的dll名称
	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID); //CreateToolhelp32Snapshot可以通过获取进程信息为指定的
                                                                    //进程、进程使用的堆[HEAP]、模块[MODULE]、线程建立一个快照。
	bMore = Module32First(hSnapshot, &me);
	for (; bMore; bMore = Module32Next(hSnapshot, &me))         //循环找到相应的线程模块
	{
		if (!_tcsicmp((LPCTSTR)me.szModule, szDllName) || !_tcsicmp((LPCTSTR)me.szExePath, szDllName))
		{
			bFound = TRUE;
			break;
		}
	}
	if (!bFound)
	{
		CloseHandle(hSnapshot);
		return FALSE;
	}
	if (!(hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)))   //与注入相似，只不过不用分配内存空间，而且是调用的FreeLibrary来进行释放
	{
		_tprintf(L"OpenProcess(%d) failed!!! [%d]\n,", dwPID, GetLastError());
		return FALSE;
	}
	hModule = GetModuleHandle(L"Kernel32.dll");
	pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hModule, "FreeLibrary");
	hThread = CreateRemoteThread(hProcess, NULL, 0, pThreadProc, me.modBaseAddr, 0, NULL);
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	CloseHandle(hProcess);
	CloseHandle(hSnapshot);
	return TRUE;
}


int _tmain(int argc, TCHAR* argv[])
{
	if (argc != 3)
	{
		_tprintf(L"USAGE : %s <pid> <dll_path>\n", argv[0]);
		return 1;
	}

	
		//更改privilege
	if (!SetPrivilege(SE_DEBUG_NAME, TRUE))
			return 1;
	if (EjectDll((DWORD)_tstol(argv[1]),argv[2]))
			_tprintf(L"EjectDll(%s,\"%s\")success!!!\n", argv[1], argv[2]);
	else
			_tprintf(L"EjectDll(%ds,\"%s\")failed!!!\n", argv[1], argv[2]);
	
	return 0;
}

